import { ref, watchEffect } from 'vue';

export default function useImageLoader(
	images: any,
	preloadLimit: number = 50,
	delayMs: number = 200
) {
	const loading = ref(false);
	const progress = ref(0);
	let timer: any = null;
	// 核心预加载方法
	const preloadImages = async (imgs: any[]) => {
		loading.value = true;
		// 仅取前N张图片
		const limitedImgs = imgs.slice(0, preloadLimit); 
		const total = limitedImgs.length;
		let loadedCount = 0;
		// const startTime = Date.now().valueOf();
		try {
			await Promise.all(
				limitedImgs.map((url: any) =>
					new Promise((resolve, reject) => {
						const img = new Image();
						img.src = url;
						img.onload = () => {
							loadedCount++;
							progress.value = Math.round((loadedCount / total) * 100);
							resolve(url);
						};
						img.onerror = () => reject(new Error(`Failed to load: ${url}`));
					}).catch((e) => {
						console.error(e);
					})
				)
			);
		} finally {
			timer && clearTimeout(timer);
			timer = setTimeout(() => {
				loading.value = false;
			}, delayMs);
		}
	};

	// 自动监听活动平台变化
	watchEffect(() => {
		if (images.value?.length) {
			preloadImages(images.value);
		}
	});


	return { loading, progress };
}
